<template>
  <!-- 工商信息 -->
  <div class="shop-business component-shop-process-business">
    <!-- native modifier has been removed, please confirm whether the function has been affected  -->
    <el-form
      ref="companyInfoFormRef"
      :model="companyInfoForm"
      :rules="companyInfoRule"
      label-width="auto"
      @submit.prevent
    >
      <div class="ci-wrapper">
        <div class="left-info">
          <el-form-item
            :label="$t('shopProcess.creditCode')"
            prop="creditCode"
          >
            <el-input
              v-model="companyInfoForm.creditCode"
              maxlength="20"
              :placeholder="$t('shopProcess.creditCodeInputTips')"
              :disabled="isNotEdit"
            />
          </el-form-item>
          <el-form-item
            :label="$t('shopProcess.firmName')"
            prop="firmName"
          >
            <el-input
              v-model="companyInfoForm.firmName"
              maxlength="50"
              :placeholder="$t('shopProcess.firmNameInputTips')"
              :disabled="isNotEdit"
              @blur="
                companyInfoForm.firmName =
                  companyInfoForm.firmName ?
                    removeHeadAndTailSpaces(companyInfoForm.firmName) :
                    companyInfoForm.firmName
              "
            />
          </el-form-item>
          <el-form-item
            :label="$t('shopProcess.residence')"
            prop="residence"
          >
            <el-input
              v-model="companyInfoForm.residence"
              maxlength="50"
              :placeholder="$t('shopProcess.residenceInputTips')"
              :disabled="isNotEdit"
              @blur="
                companyInfoForm.residence =
                  companyInfoForm.residence ?
                    removeHeadAndTailSpaces(companyInfoForm.residence) :
                    companyInfoForm.residence
              "
            />
          </el-form-item>
          <el-form-item
            :label="$t('shopProcess.representative')"
            prop="representative"
          >
            <el-input
              v-model="companyInfoForm.representative"
              maxlength="20"
              :placeholder="$t('shopProcess.representativeInputTips')"
              :disabled="isNotEdit"
              @blur="
                companyInfoForm.representative =
                  companyInfoForm.representative ?
                    removeHeadAndTailSpaces(companyInfoForm.representative) :
                    companyInfoForm.representative
              "
            />
          </el-form-item>
          <el-form-item
            v-if="paySettlementType===1"
            :label="$t('allinpay.corporateIdentityCard')"
            prop="legalIds"
          >
            <el-input
              v-model="companyInfoForm.legalIds"
              maxlength="18"
              :placeholder=" $t('allinpay.pleaseEnterIDCard')"
              :disabled="isNotEdit"
            />
          </el-form-item>
          <el-form-item
            v-if="paySettlementType===1"
            :label="$t('allinpay.legalPhone')"
            prop="legalPhone"
          >
            <el-input
              v-model="companyInfoForm.legalPhone"
              maxlength="11"
              :placeholder="$t('allinpay.pleaseEnterLegalPhone')"
              :disabled="isNotEdit"
              @input="(val)=>{companyInfoForm.legalPhone=val.replace(/[^\d]/g,'')}"
            />
          </el-form-item>
          <!-- 注册资本 -->
          <el-form-item
            :label="$t('shopProcess.capital')"
            class="capital-int"
            prop="capital"
          >
            <!-- native modifier has been removed, please confirm whether the function has been affected  -->
            <el-input
              v-model="companyInfoForm.capital"
              :disabled="isNotEdit"
              type="text"
              @input="changeNum"
              @keydown="channelInputLimit"
            >
              <template #append>
                <el-button>
                  {{ $t("shopProcess.tenThousandYuan") }}
                </el-button>
              </template>
            </el-input>
            <!-- <span class="price-unit-text">{{$t("shopProcess.tenThousandYuan")}}</span> -->
          </el-form-item>
          <el-form-item
            :label="$t('shopProcess.fountTime')"
            prop="foundTime"
            class="found-time"
          >
            <el-date-picker
              v-model="companyInfoForm.foundTime"
              type="date"
              value-format="YYYY-MM-DD hh:mm:ss"
              :placeholder="$t('admin.seleData')"
              :disabled="isNotEdit"
              :disabled-date="pickerOptions.disabledDate"
            />
          </el-form-item>
          <el-form-item
            :label="$t('shopProcess.businessTime')"
            prop="startTime"
          >
            <div style="display: flex">
              <el-date-picker
                v-model="companyInfoForm.startTime"
                style="width:150px;"
                type="date"
                value-format="YYYY-MM-DD hh:mm:ss"
                :placeholder="$t('shopProcess.startTime')"
                :disabled="isNotEdit"
                clearable
                @change="onValidateTime('startTime')"
              />
              <span style="margin: 0 10px">-</span>
              <span class="end-time">
                <el-date-picker
                  ref="endTimeRef"
                  v-model="companyInfoForm.endTime"
                  style="width:150px;"
                  type="date"
                  value-format="YYYY-MM-DD hh:mm:ss"
                  :placeholder="(isNotEdit && !companyInfoForm.endTime && companyInfoForm.startTime) ? '' : $t('shopProcess.endTime')"
                  clearable
                  :disabled="isNotEdit || !companyInfoForm.startTime"
                  @change="onValidateTime('endTime')"
                />
                <span
                  v-if="isNotEdit && !companyInfoForm.endTime && companyInfoForm.startTime"
                  class="text"
                >
                  {{ $t('shopProcess.noFixedTerm') }}
                </span>
              </span>
            </div>
          </el-form-item>
          <el-form-item
            :label="$t('shopProcess.businessScope')"
            prop="businessScope"
            style="margin-bottom:30px;"
          >
            <el-input
              v-model="companyInfoForm.businessScope"
              type="textarea"
              resize="none"
              :rows="4"
              :placeholder="$t('shopProcess.businessScopeInputTips')"
              maxlength="500"
              :disabled="isNotEdit"
              @blur="
                companyInfoForm.businessScope =
                  companyInfoForm.businessScope ?
                    removeHeadAndTailSpaces(companyInfoForm.businessScope) :
                    companyInfoForm.businessScope
              "
            />
          </el-form-item>
        </div>

        <div class="right-info">
          <div class="license-content-box">
            <el-form-item
              :label="$t('shopProcess.businessLicense')"
              prop="businessLicense"
            >
              <div class="license-content">
                <img-upload
                  v-if="applyStatus !== 0 || (applyStatus === 0 && !companyInfoForm.businessLicense)"
                  v-model="companyInfoForm.businessLicense"
                  @input="imgChange(companyInfoForm.businessLicense, 'businessLicense')"
                />
                <el-image
                  v-if="applyStatus === 0 && companyInfoForm.businessLicense"
                  class="rotating-img"
                  :src="checkFileUrl(companyInfoForm.businessLicense)"
                  :preview-src-list="[checkFileUrl(companyInfoForm.businessLicense)]"
                />
                <div class="example-box">
                  <img
                    src="@/assets/img/example-img/Business-license.png"
                    alt
                  >
                  <div class="tips">
                    {{ $t('shopProcess.example') }}
                  </div>
                </div>
              </div>
              <div class="upload-tips">
                {{ $t('shopProcess.logoTips') }}
              </div>
            </el-form-item>
          </div>
          <div class="id-box">
            <div class="upload-content">
              <!-- 法人身份证 -->
              <div
                class="upload-img"
                :class="lang === 'en' ? 'en-upload-img' : 'zh-upload-img'"
              >
                <el-form-item
                  class="idcard"
                  :label="$t('shopProcess.corporateIdentityCard')"
                  prop="identityCardFront"
                >
                  <img-upload
                    v-if="applyStatus !== 0 || (applyStatus === 0 && !companyInfoForm.identityCardFront)"
                    v-model="companyInfoForm.identityCardFront"
                    @input="imgChange(companyInfoForm.identityCardFront, 'identityCardFront')"
                  />
                  <el-image
                    v-if="applyStatus === 0 && companyInfoForm.identityCardFront"
                    class="rotating-img"
                    :src="checkFileUrl(companyInfoForm.identityCardFront)"
                    :preview-src-list="[checkFileUrl(companyInfoForm.identityCardFront)]"
                  />
                </el-form-item>
                <el-form-item
                  class="idcard"
                  label-width="0"
                  prop="identityCardLater"
                >
                  <img-upload
                    v-if="applyStatus !== 0 || (applyStatus === 0 && !companyInfoForm.identityCardLater)"
                    v-model="companyInfoForm.identityCardLater"
                    @input="imgChange(companyInfoForm.identityCardLater, 'identityCardLater')"
                  />
                  <el-image
                    v-if="applyStatus === 0 && companyInfoForm.identityCardLater"
                    class="rotating-img"
                    :src="checkFileUrl(companyInfoForm.identityCardLater)"
                    :preview-src-list="[checkFileUrl(companyInfoForm.identityCardLater)]"
                  />
                </el-form-item>
              </div>

              <div class="example-left">
                <div class="upload-example">
                  <div class="example-box">
                    <img
                      src="@/assets/img/example-img/idcard1.png"
                      alt
                    >
                    <div class="tips">
                      {{ $t('shopProcess.identityCardFront') }}
                    </div>
                  </div>
                  <div class="example-box">
                    <img
                      src="@/assets/img/example-img/idcard2.png"
                      alt
                    >
                    <div class="tips">
                      {{ $t('shopProcess.identityCardLater') }}
                    </div>
                  </div>
                </div>
                <div class="upload-tips">
                  {{ $t('shopProcess.identityCardTips') }}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="footer">
        <div
          v-if="applyStatus !== 0 && applyStatus !== 1"
          class="btn-row"
        >
          <div
            class="default-btn"
            @click="toPrevStep"
          >
            {{ $t("shopProcess.previousStep") }}
          </div>
          <div
            class="default-btn primary-btn"
            @click="saveCompanyInfo"
          >
            {{ $t("shopProcess.submitAndNextStep") }}
          </div>
        </div>
        <div
          v-if="applyStatus === 0 || applyStatus === 1"
          class="btn-row"
        >
          <div
            class="default-btn"
            @click="toPrevStep"
          >
            {{ $t("shopProcess.seePreviousStep") }}
          </div>
          <div
            class="default-btn primary-btn"
            @click="viewNextStep"
          >
            {{ $t("shopProcess.seeNextStep") }}
          </div>
        </div>
      </div>
    </el-form>
  </div>
</template>

<script setup>
import moment from 'moment'
import { isCreditCode, validNoEmptySpace, removeHeadAndTailSpaces, checkIDCard } from '@/utils/validate.js'
import { ElMessage } from 'element-plus'

const props = defineProps({
  // 申请步骤 2.工商信息
  applyStep: {
    default: 2,
    type: [String, Number]
  },
  // 是否不可以编辑信息, 当申请状态为待审核时不能编辑
  isNotEdit: {
    default: false,
    type: Boolean
  },
  // 店铺申请状态 0：未审核 1：已通过 -1：未通过 -2：未提交过申请
  applyStatus: {
    default: 0,
    type: [String, Number]
  }
})
const emit = defineEmits(['toPrevStep', 'viewNextStep', 'toNextStep'])

const lang = reactive(window.localStorage.getItem('bbcLang')) // 语言

// 第二步---工商信息
const companyInfoForm = ref({
  creditCode: '',
  firmName: '',
  residence: '',
  representative: '',
  capital: '',
  foundTime: '',
  startTime: '',
  endTime: '',
  businessScope: '',
  // 上传的图片或pdf
  businessLicense: '',
  identityCardFront: '',
  identityCardLater: ''
})

// 成立日期：今日之前可选
const pickerOptions = reactive({
  disabledDate (time) {
    const date = moment().add(0, 'days').startOf('days')
    return (
      time.getTime() >= date.valueOf()
    )
  }
})

const vaildCreditCode = (rule, value, callback) => {
  if (!isCreditCode(value)) {
    callback(new Error($t('shopProcess.creditCodeErrorTips')))
  } else {
    callback()
  }
}
const validEmptyTab = (rule, value, callback) => {
  if (validNoEmptySpace(value)) {
    callback(new Error($t('shopProcess.inputAllSpace')))
  } else {
    callback()
  }
}

const validIDCard = (rule, value, callback) => {
  if (!value || !checkIDCard(value)) {
    callback(new Error('请输入正确的法人身份证'))
  } else {
    callback()
  }
}
const validateMobile = (rule, value, callback) => {
  if (!isMobile(value)) {
    callback(new Error($t('输入正确的联系方式')))
  } else {
    callback()
  }
}
const companyInfoRule = {
  creditCode: [
    { required: true, message: $t('shopProcess.creditCodeInputTips'), trigger: 'blur' },
    { validator: vaildCreditCode, trigger: 'blur' }
  ],
  firmName: [
    { required: true, message: $t('shopProcess.firmNameNotEmpty'), trigger: 'blur' },
    { validator: validEmptyTab, trigger: 'blur' }
  ],
  residence: [
    { validator: validEmptyTab, trigger: 'blur' }
  ],
  businessScope: [
    { required: true, message: $t('shopProcess.businessScopeNotEmpty'), trigger: 'blur' },
    { validator: validEmptyTab, trigger: 'blur' }
  ],
  representative: [
    { required: true, message: $t('shopProcess.representativeNotEmpty'), trigger: 'blur' },
    { validator: validEmptyTab, trigger: 'blur' }
  ],
  businessLicense: [
    { required: true, message: $t('shopProcess.businessLicenseNotEmpty'), trigger: 'change' }
  ],
  identityCardFront: [
    { required: true, message: $t('shopProcess.identityCardFrontNotEmpty'), trigger: 'change' }
  ],
  identityCardLater: [
    { required: true, message: $t('shopProcess.identityCardLaterNotEmpty'), trigger: 'change' }
  ],
  legalIds: [
    { required: true, message: $t('allinpay.corporateIdentityCardNotEmpty'), trigger: 'blur' },
    { validator: validIDCard, trigger: 'blur' }
  ],
  legalPhone: [
    { required: true, message: $t('allinpay.legalPhoneNotEmpty'), trigger: 'blur' },
    { validator: validateMobile, trigger: 'blur' }
  ]
}
const allinPayStore = useAllinpayStore()
const paySettlementType = computed(() => {
  return allinPayStore.paySettlementType
})

onMounted(() => {
  if (props.applyStep === 2) {
    getCompanyInfo()
  }
})

const companyInfoFormRef = ref(null)
/**
 * 图片的值发生改变，重新校验对应表单字段
 */
const imgChange = (value, prop) => {
  if (value) {
    companyInfoFormRef.value?.validateField(prop)
  }
}

/**
 * 获取工商信息
 */
const getCompanyInfo = () => {
  http({
    url: http.adornUrl('/shop/shopCompany'),
    method: 'get',
    params: http.adornParams({
      status: 0
    })
  }).then(({ data }) => {
    if (data) {
      companyInfoForm.value = data
    }
  })
}

/**
 * 保存工商信息
 */
const saveCompanyInfo = () => {
  companyInfoFormRef.value?.validate((valid) => {
    if (valid) {
      http({
        url: http.adornUrl('/shop/shopCompany/storage'),
        method: 'post',
        data: http.adornData(companyInfoForm.value)
      }).then(() => {
        ElMessage({
          message: $t('shopProcess.businessSaveSuccess'),
          type: 'success',
          duration: 1000,
          onClose: () => {
            toNextStep()
          }
        })
      }).catch(() => {})
    }
  })
}

/**
 * 注册资本输入框校验
 */
const changeNum = () => {
  const capital = companyInfoForm.value.capital
  companyInfoForm.value.capital = checkInput(capital)
  if (Number.parseFloat(companyInfoForm.value.capital) === 0) {
    companyInfoForm.value.capital = 0
  }
  if (Number.parseFloat(companyInfoForm.value.capital) > 99999999) {
    companyInfoForm.value.capital = 99999999
  }
}

/**
 * input输入框只允许输入正数和小数(保留小数点后两位)
 */
const checkInput = (num) => {
  if (num) {
    let tmpVal = num.replace(/[^\d^\\.]/g, '')
    const reg = /^(0|([1-9]\d*))(\.\d{1,2})?$/ // 最多允许后输入两位小数
    if (!reg.test(tmpVal)) {
      tmpVal = tmpVal + ''
      tmpVal = tmpVal.substring(0, tmpVal.indexOf('.') + 3)
      const n = (tmpVal.split('.')).length - 1
      if (n > 1) {
        tmpVal = tmpVal.substring(0, tmpVal.indexOf('.'))
      }
    }
    return tmpVal
  } else {
    return ''
  }
}

const onValidateTime = (value) => {
  if (value === 'endTime') {
    if (!companyInfoForm.value.endTime) companyInfoForm.value.endTime = undefined
  } else {
    if (!companyInfoForm.value.startTime) companyInfoForm.value.endTime = undefined
  }
  if (companyInfoForm.value.endTime && Date.parse(companyInfoForm.value.startTime) >= Date.parse(companyInfoForm.value.endTime)) {
    ElMessage({
      message: $t('shopProcess.businessStartEndTime'),
      type: 'error',
      duration: 1500
    })
    companyInfoForm.value.endTime = undefined
  }
}

/**
 * 输入框不允许输入'-'或'+'
 */
const channelInputLimit = (e) => {
  const key = e.key
  if (key === '-' || key === '+') {
    e.returnValue = false
    return false
  }
  return true
}

/**
 * 上一步
 */
const toPrevStep = () => {
  emit('toPrevStep')
}
/**
 * 查看下一步
 */
const viewNextStep = () => {
  emit('viewNextStep')
}
/**
 * 提交，下一步
 */
const toNextStep = () => {
  emit('toNextStep')
}

</script>

<style lang="scss" scoped>
@use "index";
</style>
